<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="syncName">
        <el-input
          v-model="queryParams.syncName"
          placeholder="请输入同步任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:filesync:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:filesync:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:filesync:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:filesync:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="filesyncList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="同步任务ID" align="center" prop="syncId" v-if="false" />
      <el-table-column label="任务名称" align="center" prop="syncName" />
      <el-table-column label="源服务器" align="center" prop="sourceServer" />
      <el-table-column label="目标服务器" align="center" prop="targetServer" />
      <el-table-column label="执行周期" align="center" prop="cronExpression" width="180" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="最后执行时间" align="center" prop="lastRunTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastRunTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="handleRun(scope.row)"
            v-hasPermi="['system:filesync:run']"
          >执行</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:filesync:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:filesync:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改同步任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务名称" prop="syncName">
              <el-input v-model="form.syncName" placeholder="请输入任务名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行周期" prop="cronExpression">
              <el-input v-model="form.cronExpression" placeholder="请输入执行周期" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="12">
            <el-form-item label="源服务器" prop="sourceServerId">
              <el-select v-model="form.sourceServerId" placeholder="请选择源服务器">
                <el-option
                  v-for="item in sourceServerOptions"
                  :key="item.serverId"
                  :label="item.serverName"
                  :value="item.serverId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标服务器" prop="targetServerId">
              <el-select v-model="form.targetServerId" placeholder="请选择目标服务器">
                <el-option
                  v-for="item in targetServerOptions"
                  :key="item.serverId"
                  :label="item.serverName"
                  :value="item.serverId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="12">
            <el-form-item label="源文件路径" prop="sourcePath">
              <el-input v-model="form.sourcePath" placeholder="请输入源文件路径" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标路径" prop="targetPath">
              <el-input v-model="form.targetPath" placeholder="请输入目标路径" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="12">
            <el-form-item label="文件类型" prop="fileTypes">
              <el-input v-model="form.fileTypes" placeholder="请输入文件类型，多个用逗号分隔" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="包含子目录" prop="includeSubdirectories">
              <el-switch v-model="form.includeSubdirectories" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="同步策略" prop="fileSyncStrategy">
          <el-select v-model="form.fileSyncStrategy" placeholder="请选择同步策略">
            <el-option label="完全覆盖" value="0" />
            <el-option label="增量更新" value="1" />
            <el-option label="差异同步" value="2" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFileSync, getFileSync, delFileSync, addFileSync, updateFileSync, runFileSync } from "@/api/system/filesync";
import { listServer } from "@/api/system/server";

export default {
  name: "FileSync",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      filesyncList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        syncName: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        syncName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        sourceServerId: [
          { required: true, message: "源服务器不能为空", trigger: "change" }
        ],
        targetServerId: [
          { required: true, message: "目标服务器不能为空", trigger: "change" }
        ],
        sourcePath: [
          { required: true, message: "源文件路径不能为空", trigger: "blur" }
        ],
        targetPath: [
          { required: true, message: "目标路径不能为空", trigger: "blur" }
        ],
        fileSyncStrategy: [
          { required: true, message: "同步策略不能为空", trigger: "change" }
        ]
      },
      // 源服务器选项
      sourceServerOptions: [],
      // 目标服务器选项
      targetServerOptions: []
    };
  },
  created() {
    this.getList();
    this.getServerOptions();
  },
  methods: {
    /** 查询同步任务列表 */
    getList() {
      this.loading = true;
      listFileSync(this.queryParams).then(response => {
        this.filesyncList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取服务器选项
    getServerOptions() {
      listServer({ serverType: '1' }).then(response => {
        this.sourceServerOptions = response.rows;
        this.targetServerOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        syncId: null,
        syncName: null,
        sourceServerId: null,
        targetServerId: null,
        cronExpression: null,
        sourcePath: null,
        targetPath: null,
        fileTypes: null,
        includeSubdirectories: 0,
        fileSyncStrategy: "0",
        status: "0",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.syncId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文件同步任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const syncId = row.syncId || this.ids[0]
      getFileSync(syncId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文件同步任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.syncId != null) {
            updateFileSync(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFileSync(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const syncIds = row.syncId || this.ids;
      this.$modal.confirm('是否确认删除同步任务编号为"' + syncIds + '"的数据项?').then(function() {
        return delFileSync(syncIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 执行同步任务按钮操作 */
    handleRun(row) {
      const syncId = row.syncId;
      this.$modal.confirm('是否确认执行同步任务"' + row.syncName + '"?').then(function() {
        return runFileSync(syncId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("执行成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/filesync/export', {
        ...this.queryParams
      }, `filesync_${new Date().getTime()}.xlsx`)
    }
  }
};
</script> 